package com.zhouwr.common.metadata;

import com.alibaba.fastjson.JSON;
import com.zhouwr.common.enums.ModelDataType;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @program: forallcn-iotps
 * @description: 字符串类型
 * @author: zhouwr
 * @create: 2020-11-19 15:15
 * @version：1.0
 **/
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class StringData extends AbstractData<StringData> implements DataType, Converter<String>{
    private Integer minLength = 0;
    private Integer maxLength = 9999;
    private Integer strLength = 0;
    private String value = "";
    private ModelDataType type =  ModelDataType.STRING;

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

    @Override
    public String format(Object value) {
        return String.valueOf(value);
    }

    @Override
    public String convert(Object value) {
        ValidateResult validate = validate(value);
        if(!validate.isSuccess()) {
            throw new RuntimeException("校验失败！" + validate.getErrorMsg());
        }
        this.value = value == null ? null : String.valueOf(value);
        this.strLength = value == null?0:this.value.length();
        return this.value;
    }

    @Override
    public ValidateResult validate(Object value) {
        if(this.maxLength > 0 && this.minLength >= 0){
            boolean b = (String.valueOf(value).length() <= this.maxLength) && (String.valueOf(value).length() >= this.minLength);
            if(b) {
                return ValidateResult.success(String.valueOf(value));
            } else {
                return ValidateResult.fail("值[" + value + "]不在长度["+ this.minLength + "-" +this.maxLength +"]范围内！");
            }
        }
        return ValidateResult.success(String.valueOf(value));
    }

    public static void main(String[] args) {
        StringData stringData = new StringData();
        stringData.setMaxLength(10);
        stringData.setMinLength(4);
        stringData.value = "你好 hello";

        System.out.println(JSON.toJSON(stringData));
    }
}
